package mian.java.concurrency.thread.semaphore;

import java.util.concurrent.Semaphore;

/**
 * semaphore信号量使用
 * https://bugstack.cn/md/java/interview/2020-11-18-%E9%9D%A2%E7%BB%8F%E6%89%8B%E5%86%8C%20%C2%B7%20%E7%AC%AC18%E7%AF%87%E3%80%8AAQS%20%E5%85%B1%E4%BA%AB%E9%94%81%EF%BC%8CSemaphore%E3%80%81CountDownLatch%EF%BC%8C%E5%90%AC%E8%AF%B4%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0%E5%8F%AF%E4%BB%A5%E7%94%A8%E5%88%B0%EF%BC%81%E3%80%8B.html#_1-%E5%9F%BA%E4%BA%8E-aqs-%E5%AE%9E%E7%8E%B0%E7%9A%84%E9%94%81%E6%9C%89%E5%93%AA%E4%BA%9B
 *
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2, false); // 构造函数入参，permits：信号量、fair：公平锁/非公平锁
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "蹲坑");
                    Thread.sleep(1000L);
                    System.out.println("----------------------");
                } catch (InterruptedException ignore) {
                } finally {
                    semaphore.release();
                }
            }, "蹲坑编号：" + i).start();
        }
    }
}
